import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class JavaRedis {

    private Jedis jedis;

    @Before
    public void setJedis() {
        //连接redis服务器(在这里是连接本地的)
        jedis = new Jedis("127.0.0.1", 6379);
        System.out.println("连接服务成功");
    }

    @Test
    public void testString(){
        //设置 redis 字符串数据
        jedis.set("course", "分布式集群开发与设计");
        // 获取存储的数据并输出
        System.out.println("redis course存储的字符串为: "+ jedis.get("course"));
    }

    @Test
    public void testList(){
        //存储数据到列表中
        jedis.lpush("country", "China");
        jedis.lpush("country", "USA");
        jedis.lpush("country", "Japan");
        // 获取存储的数据并输出
        List<String> list = jedis.lrange("country", 0 ,2);
        for(int i=0; i<list.size(); i++) {
            System.out.println("列表项为: "+list.get(i));
        }
    }

    @Test
    public void testHashMap(){
        Map<String,String> stu=new HashMap<>();
        stu.put("name","Wangwu");
        stu.put("age","23");
        stu.put("sex","man");
        jedis.hmset("stu",stu);

//        String name=jedis.hget("stu","name");
//        System.out.println("redies的key（stu）中的字段name的值："+name);
//
//        String age=jedis.hget("stu","age");
//        System.out.println("redies的key（stu）中的字段name的值："+age);
//
//        String sex=jedis.hget("stu","sex");
//        System.out.println("redies的key（stu）中的字段name的值："+sex);

        Map<String,String> student=jedis.hgetAll("stu");
        Set<Map.Entry<String,String>> entrySet=student.entrySet();
        for (Map.Entry<String,String> entry:entrySet){
            System.out.println(entry.getKey()+":"+entry.getValue());
        }

    }

    @Test
    public void testSortedSet(){

        jedis.zadd("stuName",1,"Zhangsan");
        jedis.zadd("stuName",2,"lisi");
        jedis.zadd("stuName",0,"wangwu");

        Set<String> students=jedis.zrange("stuName",0,3);
        for(String student:students){
            System.out.println("redist中的数据为："+student);
        }
    }

    @Test
    public void testSet(){
        //添加
        jedis.sadd("name","Zhangsan");
        jedis.sadd("name","lisi");
        jedis.sadd("name","wangwu");

       Set<String> students=jedis.smembers("name");
       for(String student:students){
           System.out.println("redist中的数据为："+student);
       }
    }

}
